package com.uzai.console.service.lly.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateFormatUtil;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.feign.turnlink.TbPwdAnalysisDto;
import com.uzai.console.entity.PyqLlyGoods;
import com.uzai.console.mapper.PyqLlyGoodsMapper;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.lly.LlyGoodsService;
import com.uzai.console.vo.feign.turnlink.TbPwdAnalysisVo;
import com.uzai.console.vo.lly.LlyGoods;
import com.uzai.console.vo.lly.LlyMiddleDetail;
import com.uzai.console.vo.lly.LlySelectedItemResulit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 老林云商品实现类
 * @author liuqi
 * @date 2022年01月16日 17:14
 */
@Service
public class LlyGoodsServiceImpl implements LlyGoodsService {

    Logger logger = LoggerFactory.getLogger(LlyGoodsServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private PyqLlyGoodsMapper pyqLlyGoodsMapper;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Async("taskExecutor")
    @Override
    public void downLoadLlyGoodsSync() {

        //限流key
        String taskLimitKet = "-downLoadLlyGoodsSync-taskLimitKey-";
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if(object != null){
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 30, TimeUnit.MINUTES);

        logger.info("-----调用老林云库自动下载商品线程--xxlJob start--");
        downLoadLlyGoods(1);

        //删除限流key
        redisTemplate.delete(taskLimitKet);
    }

    @Async("taskExecutor")
    @Override
    public void deleteLlyGoodsSync() {
        int deleteDay = DateUtil.getNowTime() - 30*24*3600;
        deleteBeforeDay(deleteDay);
    }

    private void downLoadLlyGoods(int min_id) {
        try {
            String llyMaterialApi = uzaiConsoleSysConfig.getLlyMaterialApi();
            llyMaterialApi = llyMaterialApi + "?page=" + min_id;
            ResponseEntity<String> response = restTemplate.getForEntity(llyMaterialApi, String.class);
            if (response!=null && response.getStatusCode() == HttpStatus.OK){
                //远程调用失败，获取msg异常信息，根据自己的业务进行合理处理
                LlySelectedItemResulit llySelectedItemResulit = JSONObject.parseObject(response.getBody(), LlySelectedItemResulit.class);
                if(llySelectedItemResulit != null && Tools.getInteger(llySelectedItemResulit.getCode()).intValue() == 1){
                    List<LlyGoods> llyGoodsList = JSONObject.parseArray(JSONObject.toJSONString(llySelectedItemResulit.getData()), LlyGoods.class);
                    if (llyGoodsList != null && llyGoodsList.size() > 0){
                        llyGoodsAdd(llyGoodsList);
                        //如果本页还有数据，则请求下一页，最多拿5页
                        if(min_id <= 5){
                            min_id ++;
                            downLoadLlyGoods(min_id);
                        }else {
                            return;
                        }
                    }else {
                        return;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("-----downLoadLlyGoods sync err={}", e.getMessage());
        }
    }

    private void llyGoodsAdd(List<LlyGoods> llyGoodsList) {
        int now = DateUtil.getNowTime();
        if (llyGoodsList==null || llyGoodsList.size() ==0 ){
            return ;
        }

        logger.info("---老林库商品下载--size={}", llyGoodsList.size());

        for (LlyGoods llyGoods : llyGoodsList){

            String resourseType = llyGoods.getResource_type();
            if(StringUtils.isBlank(resourseType)){
                continue;
            }

            String description = llyGoods.getDescription();
            if(StringUtils.isBlank(description)){
                continue;
            }

            //包含下面条件，则跳过不入库
            if(description.contains("pub.alimama.com") || description.contains("s.m.taobao.com")){ //定向或者签到
                continue;
            }

            //创建时间
            String full_time =  llyGoods.getFull_time();
            if(StringUtils.isBlank(full_time)){
                continue;
            }

            if(resourseType.equals("单品")){
                //查询今天该订单是否存在，如果存在，则不处理
                String addDay = full_time.substring(0, 10);
                PyqLlyGoods pyqLlyGoods = pyqLlyGoodsMapper.selectByLlyidAndAddDay(llyGoods.getId(), addDay);
                if (pyqLlyGoods == null){
                    //在判断朋友圈内容是否重复，重复则不入库
                    String content = String2Json(Tools.getStr(llyGoods.getContent()));
                    PyqLlyGoods pyqLlyGoods_content = pyqLlyGoodsMapper.selectByContentAndAddDay(content, addDay);
                    if(pyqLlyGoods_content == null){
                        pyqLlyGoods = new PyqLlyGoods();
                        pyqLlyGoods.setId(IdWorker.getId());
                        pyqLlyGoods.setLlyid(llyGoods.getId());
                        pyqLlyGoods.setTitle(llyGoods.getTitle());
                        pyqLlyGoods.setUrl(llyGoods.getUrl());
                        pyqLlyGoods.setType(llyGoods.getType());
                        pyqLlyGoods.setCreateby(llyGoods.getCreateBy());
                        pyqLlyGoods.setTime(llyGoods.getTime());
                        pyqLlyGoods.setSn(llyGoods.getSn());
                        pyqLlyGoods.setPv(llyGoods.getPv());
                        pyqLlyGoods.setResourceType(llyGoods.getResource_type());
                        pyqLlyGoods.setPic(llyGoods.getPic());
                        pyqLlyGoods.setDescription(String2Json(Tools.getStr(description)));
                        pyqLlyGoods.setContent(content);
                        pyqLlyGoods.setFullTime(Tools.getStr(full_time));
                        pyqLlyGoods.setFavorite(Tools.getStr(llyGoods.getFavorite()));
                        pyqLlyGoods.setAddDay(addDay);
                        //短链接
                        String shortLink = JSONObject.toJSONString(findHttpUrlByRegex(description));
                        pyqLlyGoods.setShortlink(shortLink);
                        //短链接data
                        String data = getMiddleDetail(shortLink);
                        if(StringUtils.isBlank(data)){
                            continue;
                        }
                        pyqLlyGoods.setData(data);
                        pyqLlyGoods.setCreateTime(now);
                        pyqLlyGoods.setUpdateTime(now);
                        pyqLlyGoodsMapper.insert(pyqLlyGoods);
                    }
                }
            }
        }
    }

    /**
     * 正则表达式查找老林云商品的中间页链接
     *
     * @param content
     * @return String
     */
    public static List<String> findHttpUrlByRegex(String content) {
        List<String> strList = new ArrayList<>();
        Pattern pattern = Pattern.compile("(((https?|ftp|file)://)|([6]-[y]))[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");

        if(StringUtils.isBlank(content)){
            return strList;
        }
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            String strTemp = matcher.group(0);
            if(strTemp.contains("6-y.cn/")){
                strList.add(strTemp);
            }
        }
        return strList;
    }

    private String getMiddleDetail(String shortLinkListStr) {
        String middleDetail = "";
        if(StringUtils.isBlank(shortLinkListStr)){
            return middleDetail;
        }

        try {
            //返回数组
            HashMap<String, List<LlyMiddleDetail>> middleDetailMap = new HashMap<>();
            List<String> shortLinkList = JSONObject.parseArray(shortLinkListStr, String.class);
            if(shortLinkList != null && shortLinkList.size() > 0){
                for(String shortLink :  shortLinkList){
                    String llyMiddleDetailApi = uzaiConsoleSysConfig.getLlyMiddleDetailApi();
                    llyMiddleDetailApi = llyMiddleDetailApi + "?url=" + shortLink;
                    ResponseEntity<String> response = restTemplate.getForEntity(llyMiddleDetailApi, String.class);
                    if (response !=null && response.getStatusCode() == HttpStatus.OK){
                        //远程调用失败，获取msg异常信息，根据自己的业务进行合理处理
                        LlySelectedItemResulit llySelectedItemResulit = JSONObject.parseObject(response.getBody(), LlySelectedItemResulit.class);
                        if(llySelectedItemResulit != null && Tools.getInteger(llySelectedItemResulit.getCode()).intValue() == 1){
                            List<LlyMiddleDetail> llyMiddleDetailList = JSONObject.parseArray(JSONObject.toJSONString(llySelectedItemResulit.getData()), LlyMiddleDetail.class);
                            if (llyMiddleDetailList != null && llyMiddleDetailList.size() > 0){
                                for (LlyMiddleDetail llyMiddleDetail : llyMiddleDetailList){
                                    String pic = Tools.getStr(llyMiddleDetail.getPic());
                                    if(pic.contains("http://6-y.cn/")){
                                        return middleDetail;
                                    }
                                    String content = llyMiddleDetail.getContent();
                                    if(StringUtils.isNotBlank(content)){

                                        //包含下面条件，则跳过不入库
                                        if(content.contains("pub.alimama.com") || content.contains("s.m.taobao.com")){ //定向或者签到
                                            return middleDetail;
                                        }

                                        //查询出文字内容中的淘口令
                                        String pwd = Tools.findTbPwdByRegex(content);
                                        //解析淘口令
                                        if(StringUtils.isNotBlank(pwd)){
                                            TbPwdAnalysisDto tbPwdAnalysisDto = new TbPwdAnalysisDto();
                                            tbPwdAnalysisDto.setPwd(pwd);
                                            tbPwdAnalysisDto.setTokenId(uzaiConsoleSysConfig.getSystemDefaultTokenId());
                                            UzaiRespVo<TbPwdAnalysisVo> uzaiRespVo = uzaiTurnlinkFeignService.tbPwdAnalysis(tbPwdAnalysisDto);
                                            if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){//解析成功
                                                TbPwdAnalysisVo tbPwdAnalysisVo = uzaiRespVo.getData();
                                                if(tbPwdAnalysisVo != null){
                                                    String itemId = Tools.getStr(tbPwdAnalysisVo.getItemId());
                                                    String bizSceneId = Tools.getStr(tbPwdAnalysisVo.getBizSceneId());
                                                    //赋值商品id和业务bizSceneId
                                                    llyMiddleDetail.setItemId(itemId);
                                                    llyMiddleDetail.setBizSceneId(bizSceneId);
                                                    //文字内容替换商品id
                                                    content = content.replace(pwd, itemId);
                                                    llyMiddleDetail.setContent(content);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            middleDetailMap.put(shortLink, llyMiddleDetailList);
                        }
                    }
                }
            }

            middleDetail = JSONObject.toJSONString(middleDetailMap);

        } catch (Exception e) {
            logger.error("-----getMiddleDetail sync err={}", e.getMessage());
        }
        return middleDetail;
    }


    private String String2Json(String str){
        str = str.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("<br>","\n");
        return str;
    }


    /**
     * 删除多少天之前的商品
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param beforeDay
     */
    private void deleteBeforeDay(int beforeDay) {
        pyqLlyGoodsMapper.deleteBeforeDay(beforeDay);
    }

    public static void main(String[] args){
        String str = "[\"·\n" +
                "\n" +
                "▫️专柜卖178元/支\uD83D\uDE49咱\uD83D\uDCB559撸\n" +
                "▫️可可之谜·奶盖洁面➕起泡网\n" +
                "\n" +
                "\uD83D\uDC496-y.cn/wpvDO6\n" +
                "\uD83D\uDC49http://cdn.6-y.cn\\/XN38YFW8BAL-2022-10-04-21-52-12356.jpg" +
                "▫️C某B平替‼️清洁控油还不拔干~\n" +
                "▫️高端货来的 强烈推荐给兄弟们\",\"·\n" +
                "▫️只有2000件！到量停券你们抓紧！\n" +
                "▫️全国排名top3工厂联合中科院研发\uD83D\uDE0E\n" +
                "▫️刘嘉玲，白冰，李湘，林允等明星推荐\",\"·\n" +
                "▫️高端货无敌好用‼泡沫绵密上脸很舒服~\n" +
                "▫️不假滑、不紧绷！清洁 控油很绝\",\"70定向：http://pub.alimama.com/portal/promo/shop/campaign/detail.htm?mode=info&campaignId=1000509611&creatorId=398660078&breadcrumb=false\"]";

        List<String> strList = findHttpUrlByRegex(str);

        System.out.println(JSONObject.toJSONString(strList));
    }
}
